#ifndef ATHREAD_H
#define ATHREAD_H

#include <QThread>
#include <QMutex>
#include <QWaitCondition>
#include <QString>
#include <QDebug>

class AThread : public QThread
{
    Q_OBJECT

public:
    AThread()
    {
        quit = false;
        needDo = false;
    }

    ~AThread()
    {
        mutex.lock();
        quit = true;
        cond.wakeOne();
        mutex.unlock();
        wait();
    }

    void run()
    {
        //...
        while(!quit)
        {
            //...
            if (needDo)
            {
                //...
                qDebug() << "AThread run from thread:" << QThread::currentThreadId();
                mutex.lock();
                needDo = false;
                mutex.unlock();

                emit sig("Athread sig");
            }
            //...
            mutex.lock();//进入休眠（可以去掉）
            cond.wait(&mutex);//进入休眠（可以去掉）
        }
    }

signals:
    void sig(const QString &s);

public slots:
    void slot(const QString &s)
    {
        mutex.lock();
        this->s = s;
        qDebug() << "AThread slot from thread:" << QThread::currentThreadId();

        if (isRunning())
        {
            cond.wakeOne();//唤醒休眠（可以去掉）
            needDo = true;
        }
        else
        {
            needDo = true;
            start();
        }
        mutex.unlock();
    }

private:
    QMutex mutex;
    QWaitCondition cond;
    bool quit;
    bool needDo;
    QString s;//接收参数
};
#endif
